#!/usr/bin/env python
# coding=utf-8

CAPTURE_FOLDER = r'D:\captures'
DB_FILENAME = 'capturedb'
INTERVAL_CAPTURE = 60

import os
import time
import datetime
import anydbm
import zlib
import win32gui, win32ui, win32con, win32api

def window_capture():
	hwnd = 0
	hwndDC = win32gui.GetWindowDC(hwnd)
	mfcDC=win32ui.CreateDCFromHandle(hwndDC)
	saveDC=mfcDC.CreateCompatibleDC()
	saveBitMap = win32ui.CreateBitmap()
	MoniterDev=win32api.EnumDisplayMonitors(None,None)
	w = MoniterDev[0][2][2]
	h = MoniterDev[0][2][3]
	#print w,h
	saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
	saveDC.SelectObject(saveBitMap)
	saveDC.BitBlt((0,0),(w, h) , mfcDC, (0,0), win32con.SRCCOPY)
	bmpname = os.tmpnam()
	saveBitMap.SaveBitmapFile(saveDC, bmpname)
	f = open(bmpname, 'rb')
	bmpcontent = f.read()
	f.close()
	os.remove(bmpname)
	return bmpcontent

def append_capture(dbn):
	bmpcontent = window_capture()
	key = time.strftime("%Y%m%d-%H%M%S")
	value = zlib.compress(bmpcontent)
	del bmpcontent
	db = anydbm.open(dbn, 'c')
	db[key] = value
	db.close()
	print key

def main():
	if os.path.isfile(CAPTURE_FOLDER):
		sys.exit(1)
	if not os.path.exists(CAPTURE_FOLDER):
		os.mkdir(CAPTURE_FOLDER)
	if not os.path.isdir(CAPTURE_FOLDER):
		sys.exit(1)
	os.chdir(CAPTURE_FOLDER)
	dbn = time.strftime("%Y%m%d-%H%M%S-") + DB_FILENAME
	while True:
		append_capture(dbn)
		time.sleep(INTERVAL_CAPTURE)

if __name__ == '__main__':
	main()

